package org.openkanban.server.dao.impl;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.openkanban.server.dao.HistoryDao;
import org.openkanban.server.domain.Board;
import org.openkanban.server.domain.History;
import org.openkanban.server.service.BoardService;
import org.openkanban.shared.util.HistoryAction;
import org.openkanban.shared.util.StatusCodes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * jpa implementation of history data access object
 */
@Repository
public class HistoryDaoJpaImpl implements HistoryDao {

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private BoardService boardService;

    @Override
    @Transactional
    public StatusCodes writeHistoryEntry(Long userId, Long parentActivityId, HistoryAction createKanban, String historyText) {
	Board parentBoard = boardService.getBoardByActivityIdLong(parentActivityId);
	return writeHistoryEntry(parentBoard.getBoardId(), userId, parentActivityId, createKanban, historyText);
    }

    @Override
    @Transactional
    public StatusCodes writeHistoryEntry(Long boardId, Long userId, Long activityId, HistoryAction historyAction, String text) {
	History newHistory = new History(userId, boardId, activityId, historyAction, text);
	entityManager.persist(newHistory);
	return StatusCodes.OK;
    }

    @Override
    @SuppressWarnings("unchecked")
    public History[] getFullBoardHistory(Long boardId) {
	Query query = entityManager.createQuery("SELECT h FROM History h WHERE h.boardId=:boardId");
	query.setParameter("boardId", boardId);
	return (History[]) query.getResultList().toArray(new History[] {});
    }

}
